package com.nf.health.app.activity.miansearch;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.nf.health.app.customview.LoadMoreRecyclerView;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.miansearch.adapter.SearchMainRecyAdapter;
import com.nf.health.app.activity.miansearch.impl.OnChecktemLinstener;
import com.nf.health.app.customview.DividerListItemDecoration;
import com.nf.health.app.customview.ShowMyTextSearchPopupWindow;
import com.nf.health.app.customview.ShowMyTextSearchPopupWindow3;
import com.nf.health.app.customview.ShowOfferMyTextSearchPopupWindow;
import com.nf.health.app.http.Act;
import com.nf.health.app.models.SearchMainDocBean;
import com.nf.health.app.service.ServiceData;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.LocationUtil;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.widget.MyMainItemAnimation;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 新版的医生详情
 * @author yyh
 */
public class MainSearchDocActivity  extends BaseActivity{
    private Context cnt;
    @Bind(R.id.titlebar_title_search_back)
    TextView titlebar_title_search_back;

    @Bind(R.id.ll_search_area)
    LinearLayout ll_search_area;
    @Bind(R.id.tv_search_area)
    TextView tv_search_area;
    @Bind(R.id.ll_search_ks)
    LinearLayout ll_search_ks;
    @Bind(R.id.tv_search_ks)
    TextView tv_search_ks;
    @Bind(R.id.ll_search_service)
    LinearLayout ll_search_service;
    @Bind(R.id.tv_search_service)
    TextView tv_search_service;
    @Bind(R.id.ll_content_search_view)
    LinearLayout ll_content_search_view;
    @Bind(R.id.swipe_search_refresh_layout)
    SwipeRefreshLayout swipe_search_refresh_layout;
    @Bind(R.id.el_main_search)
    EditText el_main_search;
    @Bind(R.id.tv_open_gps)
    TextView tv_open_gps;
    @Bind(R.id.rl_location_tip)
    RelativeLayout rl_location_tip;
    @Bind(R.id.ll_nodata)
    LinearLayout ll_nodata;
    //@Bind(R.id.recyclerView_search)
    LoadMoreRecyclerView recyclerView_search;
    private SearchMainRecyAdapter searchMainRecyAdapter;
    private List<SearchMainDocBean> listSearchMainBean = new ArrayList<>();
    private ShowMyTextSearchPopupWindow showMyTextSearchPopupWindow;
    private ShowOfferMyTextSearchPopupWindow showOfferMyTextSearchPopupWindow;
    private String area = "";String department ="";String hospitalid ="";String keywords ="于"; int pageNo =1;String servername="";
    private int pageSize= 5;
    private boolean isPullToRefreshed = true;//是不是上拉刷新还是下拉加载
    private boolean mIsRefreshing = false;//是不是上拉刷新还是下拉加载
    private boolean isOpenLoadtion = false;//是不是开启定位
    private String locationAddress;//定位到的地址
    private LinkedList<String> subLinkedList = new LinkedList<>();//医生服务选项

    Handler updateChatHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    List<SearchMainDocBean> listSearchMainBean = (List<SearchMainDocBean>) msg.obj;
                    swipe_search_refresh_layout.setRefreshing(false);
                    searchMainRecyAdapter =  new SearchMainRecyAdapter(MainSearchDocActivity.this, listSearchMainBean);
                    searchMainRecyAdapter.setDoctorCommentData(listSearchMainBean);
                    //searchMainRecyAdapter.notifyDataSetChanged();
                    setMyVisibile();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_mainsearchdocactivity);
        ButterKnife.bind(this);
        initView();
        initEdittextListener();
    }

    private void initView() {
        String source = "开启定位";
        tv_open_gps.setText( Html.fromHtml("<u>" + "<font color='#2E86F4'>" + source + "</font>" + "</u>"));
        recyclerView_search = (LoadMoreRecyclerView) findViewById(R.id.recyclerView_search);
        swipe_search_refresh_layout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        recyclerView_search.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        recyclerView_search.setLayoutManager(mLayoutManager);
        recyclerView_search.setItemAnimator(new MyMainItemAnimation());
        recyclerView_search.setAutoLoadMoreEnable(false);
        initRecycleListener();
        searchMainRecyAdapter = new SearchMainRecyAdapter(this, listSearchMainBean);
        recyclerView_search.addItemDecoration(new DividerListItemDecoration(MainSearchDocActivity.this, LinearLayoutManager.VERTICAL, 2,
                getResources().getColor(R.color.divider_line_color)));
        recyclerView_search.setAdapter(searchMainRecyAdapter);
        swipe_search_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isPullToRefreshed = true;
                mIsRefreshing = true;
                pageNo = 1;
                loadData(pageNo);
            }
        });

        recyclerView_search.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                isPullToRefreshed = false;
                pageNo++;
                loadData(pageNo);
            }
        });
        searchMainRecyAdapter.notifyDataSetChanged();
        cnt = MainSearchDocActivity.this;
        titlebar_title_search_back.setOnClickListener(this);
        ll_search_area.setOnClickListener(this);
        ll_search_ks.setOnClickListener(this);
        tv_open_gps.setOnClickListener(this);
        ll_search_service.setOnClickListener(this);
        tv_search_area.setOnClickListener(this);
        tv_search_ks.setOnClickListener(this);
        tv_search_service.setOnClickListener(this);
        loadData(1);
        getDoctorServiceList();
    }


    /**
     * 获取搜索到的数据
     */
    private void loadData(int pageNo){
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
    /**
     *根据条件进行查询
     */
    private void questionData(String keywords){
        this.keywords = keywords;
        pageNo = 1;
        isPullToRefreshed = true;
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
     /**
     * 获取医生服务下拉框
     */
    private void getDoctorServiceList(){
        provider.getDoctorServiceList();
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        switch (actionName){
            case Act.Flag.SEARCH_DOCTOR_KESHI_HOSTIPAL_FLG:
                swipe_search_refresh_layout.setRefreshing(false);
                break;
            case Act.Flag.GET_DOCTORSERVICE_LIST_FLG:
                break;
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName){
            case Act.Flag.SEARCH_DOCTOR_KESHI_HOSTIPAL_FLG:
                List<SearchMainDocBean> subListSearchMainBean =( List<SearchMainDocBean>) object;
                if(isPullToRefreshed){
                    listSearchMainBean.clear();
                    listSearchMainBean.addAll(subListSearchMainBean);
//                    if(subListSearchMainBean.size() < pageSize){
//                        recyclerView_search.setAutoLoadMoreEnable(false);
//                    }else{
//                        recyclerView_search.setAutoLoadMoreEnable(true);
//                    }
                   /* if(subListSearchMainBean.size() < pageSize){
                        recyclerView_search.notifyMoreFinish(false);
                    }else{
                        recyclerView_search.notifyMoreFinish(true);
                    }*/
                    mIsRefreshing = false;
//                    recyclerView_search.notifyMoreFinish(true);
                }else{
                    listSearchMainBean.addAll(subListSearchMainBean);
                    if(subListSearchMainBean.size() < pageSize){
                        recyclerView_search.notifyMoreFinish(false);
                    }else{
                        recyclerView_search.notifyMoreFinish(true);
                    }
                }
                Message handleMsg = updateChatHandler.obtainMessage();
                handleMsg.what = 1;
                handleMsg.obj = listSearchMainBean;
                updateChatHandler.sendMessage(handleMsg);
               /* runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipe_search_refresh_layout.setRefreshing(false);
                        searchMainRecyAdapter.setDoctorCommentData(listSearchMainBean);
                        searchMainRecyAdapter.notifyDataSetChanged();
                        setMyVisibile();
                    }
                });*/
                break;
            case Act.Flag.GET_DOCTORSERVICE_LIST_FLG:
                subLinkedList.clear();
                JSONArray array = null;
                try {
                    array = new JSONArray(object.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                    return ;
                }
                if(array.length() > 0){
                    for (int i = 0; i < array.length(); i++) {
                        String ss = array.optString(i);
                        subLinkedList.add(ss);
                    }
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.titlebar_title_search_back:
                finish();
                break;
            case R.id.tv_open_gps://开启定位
                 LocationUtil.setGoGPSMain(MainSearchDocActivity.this);
                break;
            case R.id.ll_search_area://选择区域
            case R.id.tv_search_area:
                if(showMyTextSearchPopupWindow == null){
                    showMyTextSearchPopupWindow = new ShowMyTextSearchPopupWindow(MainSearchDocActivity.this)
                            .initMyTextViewStatus(tv_search_area, tv_search_ks, tv_search_service, isOpenLoadtion)
                            .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                                @Override
                                public void onClickFirstMenu(String mainResult) {
                                    questionData(mainResult);
                                }
                                @Override
                                public void onClickSecondMenu(String subResult) {
                                    questionData(subResult);
                                }
                            });
                    showMyTextSearchPopupWindow.setMyListData2(ServiceData.getMyCityArea2(cnt), getLocationAddress(), isOpenLoadtion);
                }else{
                    showMyTextSearchPopupWindow.refreshMylocationData( getLocationAddress(), isOpenLoadtion);
                }
                if(!showMyTextSearchPopupWindow.isShowing()){
                    showMyTextSearchPopupWindow.showAsDropDown(ll_content_search_view);
                    if(isOpenLoadtion){
                        ViewUtil.setTextImgBackground3(tv_search_area, cnt,0,R.drawable.iv_location, 0, R.drawable.iv_blue_arrowup, 0);
                    }else{
                        ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,  0, R.drawable.iv_blue_arrowup, 0);
                    }
                }
                break;
            case R.id.tv_search_ks://选择科室
            case R.id.ll_search_ks:
                if(showOfferMyTextSearchPopupWindow == null){
                    showOfferMyTextSearchPopupWindow = new ShowOfferMyTextSearchPopupWindow(MainSearchDocActivity.this)
                            .initMyTextViewStatus(tv_search_ks, tv_search_ks, tv_search_service, isOpenLoadtion)
                            .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                                @Override
                                public void onClickFirstMenu(String mainResult) {
                                    questionData(mainResult);
                                }
                                @Override
                                public void onClickSecondMenu(String subResult) {
                                    questionData(subResult);
                                }
                            });
                    showOfferMyTextSearchPopupWindow.setMyListData2(ServiceData.getMyOfferData(cnt));
                }else{
                    showOfferMyTextSearchPopupWindow.showMyMuneRefresh();
                }
                if(!showOfferMyTextSearchPopupWindow.isShowing()){
                    showOfferMyTextSearchPopupWindow.showAsDropDown(ll_content_search_view);
                    ViewUtil.setTextImgBackground2(tv_search_ks, cnt, ViewUtil.TextMode.RIGHT, 0, R.drawable.iv_blue_arrowup);
                }
                break;
            case R.id.tv_search_service://选择服务
            case R.id.ll_search_service:
                ShowMyTextSearchPopupWindow3 showMyTextSearchPopupWindow3 = null;
                if(showMyTextSearchPopupWindow3 == null){
                    showMyTextSearchPopupWindow3 = new ShowMyTextSearchPopupWindow3(MainSearchDocActivity.this)
                            .initMyTextViewStatus(tv_search_area, tv_search_ks, tv_search_service)
                            .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                                @Override
                                public void onClickFirstMenu(String mainResult) { }
                                @Override
                                public void onClickSecondMenu(String subResult) {
                                    questionData(subResult);
                                }
                            });
                    showMyTextSearchPopupWindow3.setMyListData(subLinkedList);
                }else{
                    showMyTextSearchPopupWindow.refreshMylocationData(getLocationAddress(),isOpenLoadtion);
                }
                if(!showMyTextSearchPopupWindow3.isShowing()){
                    showMyTextSearchPopupWindow3.showAsDropDown(ll_content_search_view);
                    ViewUtil.setTextImgBackground2(tv_search_service, cnt, ViewUtil.TextMode.RIGHT, 0, R.drawable.iv_blue_arrowup);
                }
                break;

        }
    }
    private void initEdittextListener() {
        el_main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    String someQuestion = el_main_search.getText().toString();
                    if (TextUtils.isEmpty(someQuestion)) {
                        GetToast.useString(cnt, "条件不能为空");
                        return false;
                    }
                    questionData(someQuestion);
                    return false;
                }
                return false;

            }

        });
    }

    /**
     * 定位相关
     */
    public void initMyLocation(){
        if(!LocationUtil.isOpenGPS(this)){
            isOpenLoadtion = false;
        }else{
            isOpenLoadtion = true;
        }
        if(showMyTextSearchPopupWindow != null && showMyTextSearchPopupWindow.isShowing()){
            if(!isOpenLoadtion){
                rl_location_tip.setVisibility(View.VISIBLE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt,0, 0, 0, R.drawable.iv_blue_arrowup, 0);//iv_blue_arrowup  inquiey_detail_arrowdown
            }else{
                rl_location_tip.setVisibility(View.GONE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, R.drawable.iv_location, 0, R.drawable.iv_blue_arrowup, 0);
            }
        }else{
            if(!isOpenLoadtion){
                rl_location_tip.setVisibility(View.VISIBLE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt,0, 0, 0, R.drawable.inquiey_detail_arrowdown, 0);
            }else{
                rl_location_tip.setVisibility(View.GONE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
            }
        }
        LocationUtil.initial(cnt, new LocationUtil.CallAddressBack() {
            @Override
            public void complete(double latitude, double longitude, String address) {
                // TODO Auto-generated method stub
                String longitudeStr = String.valueOf(longitude);
                String latitudeStr = String.valueOf(latitude);
                setLocationAddress(address);
                LogUtil.e("yuyahao", "经：" + longitudeStr + " wei: " + " longitude " + latitudeStr + "  地主： " + address);
            }

            @Override
            public void callRemainQuestFaild() {
                LogUtil.e("yuyahao", "地址获取失败");
            }
        });
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        initMyLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    public void setLocationAddress(String locationAddress) {
        this.locationAddress = locationAddress;
    }
    public void setMyVisibile() {//List<SearchMainDocBean> listSearchMainBean
         if(listSearchMainBean.size() == 0){
             ll_nodata.setVisibility(View.VISIBLE);
             swipe_search_refresh_layout.setVisibility(View.GONE);
         }else{
             ll_nodata.setVisibility(View.GONE);
             swipe_search_refresh_layout.setVisibility(View.VISIBLE);
         }
    }
    public void initRecycleListener(){
        recyclerView_search.setOnTouchListener(
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (mIsRefreshing) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        );
    }

    public String getLocationAddress() {
        return locationAddress;
    }

}
